import { ref, shallowRef, watch } from 'vue'
import type { Ref } from 'vue'
import type { ApiResult } from '@/utils/request'

export function usePage(
  request: (params: any) => Promise<ApiResult<any>>,
  queryParams: Ref<Record<string, unknown>>
) {
  const loading = ref<boolean>(false)
  const total = ref<number>(0)
  const tableData = shallowRef<Record<string, unknown>[]>([])
  const pageData = ref<Record<string, unknown>>({
    pageNum: 1,
    pageSize: 15
  })

  const getTableData = async () => {
    try {
      loading.value = true
      const { data } = await request({
        ...queryParams.value,
        ...pageData.value
      })
      tableData.value = data?.list || []
      total.value = data?.total || 0
    } finally {
      loading.value = false
    }
  }

  const pageNoChange = async (pageNo: number) => {
    pageData.value.pageNum = pageNo
    await getTableData()
  }

  const pageSizeChange = async (pageSize: number) => {
    pageData.value.pageSize = pageSize
    await getTableData()
  }

  const search = async () => {
    pageData.value.pageNum = 1
    await getTableData()
  }

  watch(
    queryParams,
    async () => {
      pageData.value.pageNum = 1
      await getTableData()
    },
    { deep: true }
  )

  return {
    loading,
    tableData,
    pageData,
    total,
    pageNoChange,
    pageSizeChange,
    search
  }
}
